/*
 * @ProjectName: 综合安防
 * @Copyright:   2018 HangZhou Hikvision System Technology Co., Ltd. All Right Reserved.
 * @address:     http://www.hikvision.com
 * @date:        2018年01月29日 14:21
 * @description: 本内容仅限于杭州海康威视系统技术公有限司内部使用，禁止转发.
 */
package com.capsule.chapter.queue;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * <p>
 *  消息缓冲队列
 *  LinkedBlockingQueue队列，自带队列阻塞功能，免去线程安全控制
 * </p>
 *
 * @author xiachaoyang
 * @version V1.0
 * @date 2018年07月04日 9:24
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2018年07月04日
 * @modify reason: {方法名}:{原因}
 * ...
 */
public class PushBlockQueue  extends LinkedBlockingQueue<Object> {

    /** 静态内部类式单例*/
    private static class SingletonHolder{
        private static final PushBlockQueue instance = new PushBlockQueue();
    }

    private PushBlockQueue(){}

    public static final PushBlockQueue getInstance(){
        return SingletonHolder.instance;
    }

    private boolean flag = false;

    //线程池
    private static ExecutorService es = Executors.newFixedThreadPool(10);

    /**
     * 队列监听启动
     */
    public void start(){
        if(!this.flag){
            this.flag = true;
        }else{
            throw new IllegalArgumentException("队列已处于启动状态,不允许重复启动.");
        }
        new Thread(new Runnable(){
            @Override
            public void run() {
                while(flag){
                    try {
                        Object obj = take();//使用阻塞模式获取队列消息
                        //将获取消息交由线程池处理
                        es.execute(new PushBlockQueueHandler(obj));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    /**
     * 停止队列监听
     */
    public void stop(){
        this.flag = false;
    }
}
